// const querystring = require('querystring');


//key/value字符串和对象的转换
const querystring = {
	stringify(obj) {
		let arr = []
		for (let key in obj) {
			const value = obj[key];
			arr.push(`${key}=${value}`)
		}
		return arr.join('&');
	},
	parse(str) {
		let obj = {}
		str.split('&').forEach(str => {
			let arr = str.split('=')
			obj[arr[0]] = arr[1];
		})
		return obj;
	}
}


/**
 * type:即协议类型，参考值，json, text默认为key/value类型
 */
const http = (url, param = {}, method = 'get', type) => {
	//解构出两种参数
	let { query, body, ...other } = param;
	if (!query && !body) {
		/******************************************
		 * 如果两者都没有，则为普通传参
		 * 则需要将param分配给query或者body
		 * 分配原则按照method
		 ******************************************/
		if (['post', 'put'].includes(method.toLowerCase())) {
			//分配给body
			body = param;
		} else {
			//分配给query
			query = param;
		}
	}

	let queryStr = '';
	if (query) {
		//必须构造字符串参数
		//参数转化为字符串
		queryStr = querystring.stringify(query);
		//判断原url中是否有？
		if (url.includes('?')) {
			url = `${url}&${queryStr}`;
		} else {
			url = `${url}?${queryStr}`;
		}
	}

	let bodyStr = undefined;
	let contentType = undefined;
	if (body) {
		if (type === 'json') {
			bodyStr = JSON.stringify(body)
			contentType = 'application/json'
		} else if (type === 'text') {
			bodyStr = body;
			contentType = 'application/text'
		} else if (type === 'attach') {
			//附件
			bodyStr = body;
			contentType = 'multipart/form-data'
		} else {
			bodyStr = querystring.stringify(body)
			contentType = 'application/x-www-form-urlencoded'
		}
	}

	return new Promise((resolve, reject) => {
		let xhr = null
		//初始化
		if (window.ActiveXObject) {
			xhr = new window.ActiveXObject();
		} else {
			xhr = new window.XMLHttpRequest();
		}
		//打开
		xhr.open(method, url)
		//设置协议头部
		if (['post', 'put'].includes(method.toLowerCase())) {
			xhr.setRequestHeader('Content-Type', contentType)
		}
		//发送
		xhr.send(bodyStr)
		//监听异步响应
		xhr.onreadystatechange = () => {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					//服务器响应成功
					resolve(JSON.parse(xhr.responseText))
				} else {
					//服务器响应失败
					reject(xhr.responseText)
				}
			}
		}
	})

}
